package com.yanqu.road.server.gameplayer.module.workshop;

import com.yanqu.road.dao.impl.wingroom.UserWorkShopDataDaoImpl;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.wingroom.config.WingRoomFurnitureConfig;
import com.yanqu.road.entity.wingroom.workshop.UserWorkShopData;
import com.yanqu.road.entity.wingroom.workshop.WorkShopBuyCount;
import com.yanqu.road.entity.wingroom.workshop.WorkShopItem;
import com.yanqu.road.entity.wingroom.workshop.WorkShopPool;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.wingroom.WingRoomProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.WorkShopCommonMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.wingroom.WingRoomConfigMgr;
import com.yanqu.road.server.manger.wingroom.WingRoomMgr;
import com.yanqu.road.server.pb.WingRoomPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：zfr
 * @date ：2022/1/20 16:50
 */
public class WorkShopModule extends GeneralModule {
    private UserWorkShopData userWorkShopData;

    public WorkShopModule(GamePlayer player) {
        super(player);
    }

    public Map<Integer, WorkShopBuyCount> getBuyCountMap() {
        return userWorkShopData.getBuyCountMap();
    }

    @Override
    public boolean loadData() {
        userWorkShopData = new UserWorkShopDataDaoImpl().getUserWorkShopData(getUserId());
        initSystem();
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        if (userWorkShopData != null) {
            if (userWorkShopData.isInsertOption()) {
                new UserWorkShopDataDaoImpl().add(userWorkShopData);
            } else if (userWorkShopData.isUpdateOption()) {
                new UserWorkShopDataDaoImpl().update(userWorkShopData);
            }
        }
        return true;
    }

    //工坊购买家具
    public int workShopBuyFurniture(int furnitureId, long count) {
        if (count < 1 || count > GameConfig.MALL_BUY_MAX_COUNT) {
            return GameErrorCode.E_MALL_COUNT_NOT_ZERO;
        }
        //是否在池子里
        WorkShopItem workShopItm = findWorkShopItm(furnitureId);
        if (workShopItm == null) {
            return GameErrorCode.E_WING_ROOM_WORK_SHOP_BUY_ITEM_NO_FOUND;
        }
        //配置是否存在
        WingRoomFurnitureConfig furnitureConfig = WingRoomConfigMgr.getFurnitureConfig(furnitureId);
        if (furnitureConfig == null) {
            return GameErrorCode.E_WING_ROOM_CONFIG_NO_FOUND;
        }
        //是否限购
        if (isLimitBuy(furnitureId, count, workShopItm.getCount())) {
            return GameErrorCode.E_MALL_LIMIT_BUY;
        }

        Property consume = PropertyHelper.parseStringToProperty(furnitureConfig.getPrice());
        consume.rideProperty(count);
        //消耗是否足够
        if (!player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.WingRoom, eLogMoneyType.WingRoomWorkShopBuyCost)) {
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        WorkShopBuyCount workShopBuyCount = getBuyCountMap().get(furnitureId);
        workShopBuyCount.setBuyCount(workShopBuyCount.getBuyCount() + count);
        userWorkShopData.setUpdateOption();
        Property reward = new Property(furnitureId, BigInteger.valueOf(count));
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.WingRoom, eLogMoneyType.WingRoomWorkShopBuyGet);
        syncWorkShopBuyCount();
        return 0;
    }

    //是否限购
    private boolean isLimitBuy(int furnitureId, long count, long limitCount) {
        WorkShopBuyCount workShopBuyCount = getBuyCountMap().get(furnitureId);

        if (workShopBuyCount == null) {
            initBuyCount(furnitureId);
        }
        workShopBuyCount = getBuyCountMap().get(furnitureId);

        return workShopBuyCount.getBuyCount() + count > limitCount;
    }

    private void initBuyCount(int furnitureId) {
        WorkShopBuyCount buyCount = new WorkShopBuyCount();
        buyCount.setUserId(getUserId());
        buyCount.setFurnitureId(furnitureId);
        buyCount.setBuyCount(0L);
        buyCount.setResetTime(System.currentTimeMillis());
        buyCount.setInsertOption();
        getBuyCountMap().put(furnitureId, buyCount);
    }

    //查找工坊内的商品
    private WorkShopItem findWorkShopItm(int furnitureId) {
        WorkShopPool workShopPool = userWorkShopData.getWorkShopPool();
        if (workShopPool == null) {
            return null;
        }
        for (WorkShopItem shopItem : workShopPool.getWorkShopItemList()) {
            if (shopItem.getFurnitureId() == furnitureId) {
                return shopItem;
            }
        }
        return null;
    }
    @Override
    public void afterLogin() {
        syncWorkShopPool();
    }

    public void syncWorkShopPool() {
        WingRoomProto.WorkShopPoolTemp.Builder poolMsg = WingRoomMgr.getPoolMsg();
        if (poolMsg != null && userWorkShopData != null) {
            if (userWorkShopData.getRefreshTimes() < poolMsg.getRefreshTime() && userWorkShopData.getWorkShopPool().getRefreshTime() < poolMsg.getRefreshTime()) {
                WorkShopPool pool = WingRoomPb.parseWorkShopPool(poolMsg);
                userWorkShopData.setWorkShopPool(pool);
                userWorkShopData.setBuyCountMap(new ConcurrentHashMap<>());
            }
        }
        if (userWorkShopData != null) {
            player.sendPacket(ClientProtocol.U_WING_ROOM_WORK_SHOP_POOL_SYNC, WingRoomPb.buildUserWorkShopDataSyncMsg(userWorkShopData, GameConfig.WINGROOM_WORKSHOP_REFRESH_TIME));
        }
    }

    private void syncWorkShopBuyCount() {
        WingRoomProto.WorkShopBuyCountMsgSync.Builder syncMsg = WingRoomProto.WorkShopBuyCountMsgSync.newBuilder();
        for (WorkShopBuyCount buyCount : getBuyCountMap().values()) {
            syncMsg.addBuyCount(WingRoomPb.buildWorkShopBuyCountTemp(buyCount));
        }
        player.sendPacket(ClientProtocol.U_WING_ROOM_WORK_SHOP_BUY_COUNT_SYNC, syncMsg);
    }


    public WorkShopBuyCount getWorkShopBuyCount(int furnitureId) {
        return getBuyCountMap().get(furnitureId);
    }


    public int refreshPool() {
        if (userWorkShopData == null) {
            return GameErrorCode.E_WING_ROOM_WORK_SHOP_DATA_NO_FOUND;
        }
        resetOneDay();
        //当前是第几次刷新
        int refreshTimes = userWorkShopData.getRefreshTimes() + 1;
        long costIngots = calcRefreshPoolCost(refreshTimes);
        if (!player.getModule(CurrencyModule.class).removeCurrency(new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(costIngots)), eLogMoneyType.WingRoom, eLogMoneyType.WingRoomWorkShopRefreshPoolCost)) {
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        userWorkShopData.getWorkShopPool().setWorkShopItemList(WorkShopCommonMgr.newPool());
        userWorkShopData.setBuyCountMap(new ConcurrentHashMap<>());
        userWorkShopData.setRefreshTimes(refreshTimes);
        userWorkShopData.setUserRefreshTime(System.currentTimeMillis());
        syncWorkShopPool();
        return 0;
    }

    private long calcRefreshPoolCost(int refreshTimes) {
        String consumeParam = GameConfig.WINGROOM_WORKSHOP_REFRESH_CONSUME;
        String[] split = consumeParam.split("\\|");
        if (refreshTimes <= split.length) {
            return Long.valueOf(split[refreshTimes - 1]);
        }
        return Long.valueOf(split[split.length - 1]);
    }

    public void resetOneDay() {
        try {
            long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp();
            if (userWorkShopData != null) {
                if (userWorkShopData.getTimesRefreshTime() < zeroTime) {
                    userWorkShopData.setRefreshTimes(0);
                    userWorkShopData.setTimesRefreshTime(zeroTime);
                }
            }
        } catch (Exception e) {
            log.error("workShop refreshTimes reset error, playerId:{}", getUserId(), e);
        }
    }

    //系统解锁
    public void initSystem() {
        if (SystemOpenMgr.systemOpen(player, eSystemId.WingRoom.getValue())) {
            initWorkShopData();
        }
    }

    private void initWorkShopData() {
        if (userWorkShopData == null) {
            userWorkShopData = new UserWorkShopData();
            userWorkShopData.setUserId(getUserId());
            WingRoomProto.WorkShopPoolTemp.Builder poolMsg = WingRoomMgr.getPoolMsg();
            if (poolMsg != null) {
                WorkShopPool pool = WingRoomPb.parseWorkShopPool(poolMsg);
                userWorkShopData.setWorkShopPool(pool);
                userWorkShopData.setBuyCountMap(new ConcurrentHashMap<>());
            }
            userWorkShopData.setTimesRefreshTime(System.currentTimeMillis());
            userWorkShopData.setInsertOption();
            syncWorkShopPool();
        }
    }
}
